package com.c6906.vdam.das.service;

import com.c6906.vdam.das.config.DasOpenStatus;
import org.springframework.stereotype.Service;
import org.springframework.web.util.UriUtils;

import javax.annotation.Resource;
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.net.URL;
import java.net.URLConnection;
import java.util.LinkedHashMap;
import java.util.Map;

@Service
public class GeoLocationService {
    private static final String AK = "POt9AL9s5BOOBtE0giPgmBlTFvJf65lF";
    @Resource
    DasOpenStatus openStatus;

    /**
     * 请求百度地图反向地理编码接口获取位置
     *
     * @param latitude  纬度
     * @param longitude 经度
     * @return 返回JSON字符串
     */
    public String getLocation(double latitude, double longitude) throws Exception {
        String URL = openStatus.getBaiduApiPrefix();

        Map<String, String> params = new LinkedHashMap<>();
        params.put("ak", AK);
        params.put("output", "json");
        params.put("coordtype", "wgs84ll");
        params.put("extensions_poi", "1");
        params.put("location", latitude + "," + longitude);

        return requestGetAK(URL, params);
    }

    /**
     * 发起 GET 请求
     */
    private String requestGetAK(String strUrl, Map<String, String> param) throws Exception {
        if (strUrl == null || strUrl.isEmpty() || param == null || param.isEmpty()) {
            return null;
        }

        StringBuilder queryString = new StringBuilder();
        queryString.append(strUrl);
        for (Map.Entry<?, ?> pair : param.entrySet()) {
            queryString.append(pair.getKey()).append("=")
                    .append(UriUtils.encode((String) pair.getValue(), "UTF-8")).append("&");
        }

        if (queryString.length() > 0) {
            queryString.deleteCharAt(queryString.length() - 1);
        }

        URL url = new URL(queryString.toString());
        URLConnection httpConnection = url.openConnection();
        httpConnection.connect();

        InputStreamReader isr = new InputStreamReader(httpConnection.getInputStream());
        BufferedReader reader = new BufferedReader(isr);
        StringBuilder buffer = new StringBuilder();
        String line;
        while ((line = reader.readLine()) != null) {
            buffer.append(line);
        }
        reader.close();
        isr.close();

        return buffer.toString();  // 返回响应结果
    }
}